package com.microframework.boot.customapi.service.impl;

import java.util.List;
import org.springframework.stereotype.Service;
import com.jfinal.plugin.activerecord.Db;
import com.microframework.boot.customapi.model.domain.Dbapi;
import com.microframework.boot.customapi.model.domain.DbapiGroup;
import com.microframework.boot.customapi.model.domain.DbapiReqArguments;
import com.microframework.boot.customapi.model.domain.DbapiSql;
import com.microframework.boot.customapi.service.IDbapiService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class DbapiServiceImpl implements IDbapiService {
    
    @Override
    public void deleteGroupByIds(String id) {
        // 开启事务，确保所有删除操作原子性
        Db.use(DbapiSql.DS_NAME).tx(() -> {
            // 递归删除所有子分组及相关数据
            deleteChildrenGroups(id);
            
            // 删除当前分组下的API请求参数
            deleteApiRelatedData(DbapiReqArguments.DS_NAME, DbapiReqArguments.TABLE_NAME, id);
            
            // 删除当前分组下的API SQL
            deleteApiRelatedData(DbapiSql.DS_NAME, DbapiSql.TABLE_NAME, id);
            
            // 删除当前分组下的API
            Db.use(Dbapi.DS_NAME).delete("delete from " + Dbapi.TABLE_NAME + " where group_id=?", id);
            
            // 最后删除分组本身
            DbapiGroup.dao.deleteById(id);
            return true;
        });
    }
    
    /**
     * 递归删除所有子分组及其相关数据
     * @param parentId 父分组ID
     */
    private void deleteChildrenGroups(String parentId) {
        List<DbapiGroup> childGroups = DbapiGroup.dao.find(
            "select id from " + DbapiGroup.TABLE_NAME + " where parent_id=?", 
            parentId
        );
        
        for (DbapiGroup childGroup : childGroups) {
            // 递归删除子分组的子分组
            deleteChildrenGroups(childGroup.getId());
            
            // 删除子分组下的API相关数据
            deleteApiRelatedData(DbapiReqArguments.DS_NAME, DbapiReqArguments.TABLE_NAME, childGroup.getId());
            deleteApiRelatedData(DbapiSql.DS_NAME, DbapiSql.TABLE_NAME, childGroup.getId());
            
            // 删除子分组下的API
            Db.use(Dbapi.DS_NAME).delete(
                "delete from " + Dbapi.TABLE_NAME + " where group_id=?", 
                childGroup.getId()
            );
            
            // 删除子分组本身
            childGroup.delete();
        }
    }
    
    /**
     * 删除API相关表数据
     * @param dsName 数据源名称
     * @param tableName 表名
     * @param groupId 分组ID
     */
    private void deleteApiRelatedData(String dsName, String tableName, String groupId) {
        Db.use(dsName).delete(
            "delete from " + tableName + " where api_id in (select id from " + Dbapi.TABLE_NAME + " where group_id=?)", 
            groupId
        );
    }
}
